const app = getApp()
import { index, list } from '../../../api/article'

Page({
  data: {
    header: app.global.headerHeight,
    theme: '',
    back: true,
    title: '发现',
    loading: true,
    loadmore: false,
    active: 0,
    banner: [],
    category: [],
    list: null,
    form: {
      page: 1,
      limit: 10,
      category: 0
    },
    abnor: {
      title: '报告，这里什么都没有发现~',
      button: ''
    }
  },
  onLoad () {
    this.setData({ loading: true, theme: app.global.theme })
    index(this.data.form).then(res => {
      const { data } = res
      this.data.form.last_page = data.list.last_page
      this.setData({
        banner: data.banner,
        category: data.category,
        list: data.list.data,
        loadmore: data.list.last_page <= 1
      })
    })
      .finally(() => {
        this.setData({ loading: false })
        wx.hideLoading()
      })
  },
  onPullDownRefresh () { /* 监听用户下拉动作*/ },
  onReachBottom () {
    if (this.data.form.page == this.data.form.last_page) {
      this.setData({ loadmore: true })
    } else {
      this.data.form.page += 1
      this.getList()
    }
  },

  // ===================methon================

  getList (res) {
    list(this.data.form).then(res => {
      const { data } = res
      this.data.list || (this.data.list = [])
      const list = this.data.list.concat(data.data)
      this.data.form.last_page = data.last_page
      this.setData({
        list: list,
        loadmore: data.last_page <= 1
      })
    })
      .finally(() => {
        this.setData({ loading: false })
        wx.hideLoading()
      })
  },

  onChange (event) {
    const index = event.detail.index
    let category = 0
    
    if (index > 0) {
      this.data.category.forEach((item, i) => {
        if (i == index - 1) category = item.id
      })
    }

    let form = this.data.form
    form.category = category
    form.page = 1
    this.setData({
      list: null,
      form: form
    });
    wx.showLoading({ title: '加载中' });
    this.getList()
  },

  redirect(event) {
    if (event.currentTarget.dataset.link) {
      app.redirect(event.currentTarget.dataset.link);
    }
  }
})